<template>
  <div class="test-case-generator">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>用例生成器</span>
        </div>
      </template>
      
      <el-form :model="formData" label-width="120px">
        <el-form-item label="需求描述">
          <el-input 
            v-model="formData.requirements" 
            type="textarea" 
            :rows="8" 
            placeholder="请输入功能需求描述..."
          ></el-input>
        </el-form-item>
        
        <el-form-item label="上传文档">
          <el-upload
            action="#"
            :multiple="true"
            :on-change="handleFileChange"
            :file-list="fileList"
            :limit="3"
            :auto-upload="false"
            accept=".pdf,.docx,.txt"
            list-type="text"
          >
            <el-button type="primary" size="small">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持PDF、Word和TXT格式</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button 
          :loading="isGenerating" 
          :disabled="isGenerating" 
          type="primary" 
          @click="generateTestCases"
        >
          {{ isGenerating ? '正在生成...' : '生成测试用例' }}
        </el-button>
        
        <el-button 
          :disabled="!hasGenerated" 
          type="success" 
          @click="downloadTestCase"
        >
          下载测试用例
        </el-button>
      </div>
      
      <el-alert
        v-if="showProgress"
        title="用例生成中"
        type="info"
        :closable="false"
        show-icon
      >
        系统正在生成测试用例，请耐心等待，请勿刷新或离开此页面...
      </el-alert>
      
      <el-alert
        v-if="successMessage"
        title="生成成功"
        type="success"
        show-icon
      >
        {{ successMessage }}
      </el-alert>
      
      <el-alert
        v-if="errorMessage"
        title="生成失败"
        type="error"
        show-icon
      >
        {{ errorMessage }}
      </el-alert>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 状态管理
const formData = ref({
  requirements: '',
});
const fileList = ref([]);
const isGenerating = ref(false);
const hasGenerated = ref(false);
const showProgress = ref(false);
const successMessage = ref('');
const errorMessage = ref('');

// 创建axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:8000/ai', // API基础URL
  timeout: 600000, // 10分钟超时
});

// 文件上传处理
const handleFileChange = (file, fileList) => {
  // 限制文件数量
  if (fileList.length > 3) {
    ElMessage.warning('最多只能上传3个文件');
    return false;
  }
  // 验证文件类型
  const allowedTypes = ['.pdf', '.docx', '.txt'];
  const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  if (!allowedTypes.includes(ext)) {
    ElMessage.error('请上传PDF、Word或TXT格式的文件');
    return false;
  }
  return true;
};

// 生成测试用例
const generateTestCases = async () => {
  // 表单验证
  if (!formData.value.requirements && fileList.value.length === 0) {
    ElMessage.error('请输入需求描述或上传相关文档');
    return;
  }

  // 准备表单数据
  const formDataToSend = new FormData();
  formDataToSend.append('text', formData.value.requirements);
  
  // 添加文件
  fileList.value.forEach(file => {
    formDataToSend.append('files', file.raw);
  });
  // 显示加载状态
  isGenerating.value = true;
  showProgress.value = true;
  errorMessage.value = '';
  successMessage.value = '';

  try {
    // 发送请求到后端API
    const response = await service.post('/aiCase', formDataToSend, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    // 处理成功响应
    hasGenerated.value = true;
    successMessage.value = `测试用例生成成功，共生成${response.data.test_case_count}条测试用例`;
    ElMessage.success('测试用例生成成功！');
  } catch (error) {
    // 处理错误
    if (error.response) {
      errorMessage.value = error.response.data.error || '服务器错误，请重试';
    } else if (error.request) {
      errorMessage.value = '请求超时，请检查网络连接';
    } else {
      errorMessage.value = error.message || '生成测试用例失败，请重试';
    }
    ElMessage.error(errorMessage.value);
  } finally {
    // 关闭加载状态
    isGenerating.value = false;
    showProgress.value = false;
  }
};

// 下载测试用例
const downloadTestCase = () => {
  if (!hasGenerated.value) {
    ElMessage.warning('请先生成测试用例');
    return;
  }

  // 直接调用后端下载接口（后端已处理文件名）
  window.open('http://127.0.0.1:8000/ai/downloadCase', '_blank');
};

// 页面加载时检查文件状态（可选）
onMounted(() => {
  // 可在此处添加检查文件是否存在的逻辑
});
</script>

<style scoped>
.test-case-generator {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 20px;
}
</style>